/*
 * Ganesa Copyright (C) 2008 Wim Crols <twimpiex@gnx.be>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package be.gnx.ganesa.application.ui;

import java.util.Vector;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

import be.gnx.ganesa.application.command.Command;
import be.gnx.ganesa.application.event.CommandStackEvent;
import be.gnx.ganesa.application.event.CommandStackListener;

public class CommandStack {

  private CTabFolder commandStackTabFolder;

  private InfoBar infoBar;

  int height = 300;

  public CommandStack(InfoBar infoBar, Ganesa ganesa, Composite parent) {
    this.infoBar = infoBar;
    createCommandStack(infoBar, ganesa, parent);
  }

  public void createCommandStack(InfoBar infoBar, Ganesa ganesa, Composite parent) {
    commandStackTabFolder = new CTabFolder(parent, SWT.TOP);
    CTabItem commandStackTabItem = new CTabItem(commandStackTabFolder, SWT.NONE);
    commandStackTabItem.setText("Command Stack");

    final Table commandStackTable = new Table(commandStackTabFolder, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
    commandStackTable.setLinesVisible(false);
    commandStackTable.setHeaderVisible(false);
    redraw(commandStackTable, ganesa.getApplication().getCommandStack().getCommands());

    commandStackTabItem.setControl(commandStackTable);

    ganesa.getApplication().getCommandStack().addCommandStackListener(new CommandStackListener() {
      @Override
      public void commandStackEventhappened(CommandStackEvent event) {
        redraw(commandStackTable, event.getCommandStack().getCommands());
      }
    });
    commandStackTabFolder.setSelection(0);
    resize();
  }

  public void resize() {
    commandStackTabFolder.setBounds(commandStackTabFolder.getParent().getClientArea().width - (infoBar.getWidth() - infoBar.getSashWidth()),
        500, infoBar.getWidth() - infoBar.getSashWidth(), height);
  }

  public void redraw(Table commandStackTable, Vector<Command> commands) {
    commandStackTable.clearAll();
    commandStackTable.setItemCount(0);
    for (Command command : commands) {
      TableItem item = new TableItem(commandStackTable, SWT.NONE);
      item.setText(0, command.displayString());
    }
  }

}
